package it.mp.acquaalta;

import java.io.Serializable;

import it.mp.acquaalta.utility.AcquaAltaBean;
import it.mp.acquaalta.utility.Allarmi;
import it.mp.acquaalta.utility.DatiAdapter;
import it.mp.acquaalta.widget.R;
import it.mp.acquaalta.widget.Setup;
import it.mp.android.qa.ActionItem;
import it.mp.android.qa.QuickAction;
import android.app.Activity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class AcquaAlta extends Activity {
	protected static final String AGGIORNAMENTO_IN_CORSO = "AGGIORNAMENTO_IN_CORSO->";
	public static final String DATI = "DATI";
	private static final String TASK = "TASK->";
	private static final String MESSAGGIO_LETTO = "MESSAGGIO_LETTO->";
	public static final String WIDGET_APERTA = "WIDGET_APERTA->";
	private ProgressDialog pd = null;
	private LoadAsyncTask task;
	private SharedPreferences pref;
	private Handler messageHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			SharedPreferences.Editor editor = pref.edit();
			switch (msg.what) {
				case (LoadAsyncTask.DOWNLOAD_ID) :
					editor.putBoolean(AcquaAlta.AGGIORNAMENTO_IN_CORSO, false);
					editor.commit();
					if (pd != null) {
						pd.dismiss();
					}
					task = null;
					Toast.makeText(AcquaAlta.this, "Caricamento avvenuto con successo!", Toast.LENGTH_SHORT).show();
					crea();
					break;
				case (LoadAsyncTask.ERRORIDENTIFIER) :
					editor.putBoolean(AcquaAlta.AGGIORNAMENTO_IN_CORSO, false);
					editor.commit();
					if (pd != null) {
						pd.dismiss();
					}

					task = null;
					Toast.makeText(AcquaAlta.this, "Errore nel caricamento!Riprova!", Toast.LENGTH_LONG).show();
					AcquaAlta.this.setProgressBarIndeterminateVisibility(false);
					break;
				case (LoadAsyncTask.PROGRESS) :
					break;
			}
		}
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.acquaalta_main);

		final ActionItem first = new ActionItem();
		first.setTitle(getResources().getString(R.string.aggiorna));
		first.setIcon(getResources().getDrawable(R.drawable.aggiorn2));

		final ActionItem second = new ActionItem();
		second.setTitle("Setup");
		second.setIcon(getResources().getDrawable(R.drawable.ruota));
		final ActionItem third = new ActionItem();
		third.setTitle(getResources().getString(R.string.riallarma));
		third.setIcon(getResources().getDrawable(R.drawable.allarm));

		pref = this.getSharedPreferences(AcquaAlta.DATI, Context.MODE_PRIVATE);
		findViewById(R.id.BTN_aggiorna).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Button btn = (Button) v;
				if (btn.getText().equals(AcquaAlta.this.getResources().getString(R.string.opzioni))) {
					final QuickAction qa = new QuickAction(v);
					first.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
							qa.dismiss();
							AcquaAlta.this.aggiornaDati();
						}
					});
					second.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
							qa.dismiss();
							Intent i=new Intent(AcquaAlta.this,Setup.class);
							startActivityForResult(i, 200000);							
						}
					});

					third.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {							
							qa.dismiss();
							Allarmi al=new Allarmi(AcquaAltaBean.valueOf(AcquaAlta.this).alBean,AcquaAlta.this);
							al.riallarma();
						}
					});
					qa.addActionItem(first);
					qa.addActionItem(second);
					SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(AcquaAlta.this);
					if (!(prefs.getBoolean("PERSISTENT", true))) {
						qa.addActionItem(third);
					}

					qa.setAnimStyle(QuickAction.ANIM_AUTO);
					qa.show();
				} else {
					aggiornaDati();
				}
			}

		});
		findViewById(R.id.BTN_grafico).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(AcquaAlta.this, AcquaAltaGrafico.class);
				startActivityForResult(intent, 1234567899);
			}
		});

		if (!pref.getBoolean(AcquaAlta.MESSAGGIO_LETTO, false)) {
			new Disclaimer(this, true).show();
		} else {

			if (savedInstanceState != null) {
				if (pref.getBoolean(AcquaAlta.AGGIORNAMENTO_IN_CORSO, false)) {
					task = (LoadAsyncTask) savedInstanceState.get(AcquaAlta.TASK);
					pd = ProgressDialog.show(AcquaAlta.this, null, "Loading...", true, false);
					task.setMessageHandler(messageHandler);
				}
			}
			crea();
		}
	}
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (pd != null) {
			outState.putSerializable(AcquaAlta.TASK, task);
			pd.dismiss();
		}
	}
	private void crea() {
		AcquaAltaBean aaBean = AcquaAltaBean.valueOf(this);
		if (aaBean.alBean != null) {

			DatiAdapter adapter = new DatiAdapter(this, R.layout.acquaalta_riga, aaBean.alBean);
			adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
			((ListView) findViewById(R.id.LV_dati)).setAdapter(adapter);
			((ListView) findViewById(R.id.LV_dati)).setOnItemSelectedListener(new OnItemSelectedListener() {
				public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				}
				public void onNothingSelected(AdapterView<?> arg0) {
				}
			});

		}
		((TextView) findViewById(R.id.TV_data_ultimo_aggiornamento)).setText(aaBean.dataUltimoAggiornamento);
		AcquaAlta.this.setProgressBarIndeterminateVisibility(false);
		Button btn = (Button) findViewById(R.id.BTN_aggiorna);
		if (pref.getBoolean(WIDGET_APERTA, false)) {
			btn.setText(R.string.opzioni);
		} else {
			btn.setText(R.string.aggiorna);
		}
	}

	final class Disclaimer extends Builder implements Serializable {
		private static final long serialVersionUID = -1076777817829790080L;
		final Context mContext;
		Disclaimer(Context context, boolean primaInstallazione) {

			super(context);
			mContext = context;
			setTitle("Disclaimer");
			setMessage(mContext.getResources().getString(R.string.disclaimer));

			DialogInterface.OnClickListener installListener = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					SharedPreferences prefs = getSharedPreferences(AcquaAlta.DATI, Context.MODE_PRIVATE);
					SharedPreferences.Editor editor = prefs.edit();
					editor.putBoolean(AcquaAlta.MESSAGGIO_LETTO, true);
					editor.commit();
					crea();
				}
			};

			DialogInterface.OnClickListener laterListener = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			};
			setPositiveButton("Ho preso visione", installListener);
			setNegativeButton("Non Accetto", laterListener);
		}
	}

	private void aggiornaDati() {
		AcquaAlta.this.setProgressBarIndeterminateVisibility(true);
		pd = ProgressDialog.show(AcquaAlta.this, null, "Loading...", true, false);
		task = new LoadAsyncTask(AcquaAlta.this, messageHandler);
		SharedPreferences.Editor editor = pref.edit();
		editor.putBoolean(AcquaAlta.AGGIORNAMENTO_IN_CORSO, true);
		editor.commit();
		task.execute();
	}
}
